package com.wedo.book.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wedo.book.mapper.AuthorMapper;
import com.wedo.book.mapper.BookMapper;
import com.wedo.book.pojo.Author;
import com.wedo.book.pojo.Book;
import com.wedo.common.pojo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@CacheConfig(cacheNames = "author")
public class AuthorService {

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private BookService bookService;

    @Cacheable(key = "'queryAuthorByAid.'+#aid")
    public Author queryAuthorByAid(Long aid) {
        return this.authorMapper.selectByPrimaryKey(aid);
    }

    @CacheEvict(value = "author", allEntries=true)
    public void saveAuthor(Author author) {
        author.setId(null);
        this.authorMapper.insertSelective(author);
    }

    @CacheEvict(value = "author", allEntries=true)
    public void updateAuthor(Author author) {
        if (!StringUtils.isBlank(author.getName())) {
            Example example = new Example(Book.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("aId",author.getId());
            List<Book> books = this.bookMapper.selectByExample(example);
            books.forEach(book -> {
                bookService.sendMsg("update",book.getId());
            });
        }
        this.authorMapper.updateByPrimaryKeySelective(author);
    }

    @CacheEvict(value = "author", allEntries=true)
    public void deleteAuthorById(Long id) {
        this.authorMapper.deleteByPrimaryKey(id);
    }

    @Cacheable(key = "'queryAuthorByPage.'+#name+'.'+#page+'.'+#rows")
    public PageResult<Author> queryAuthorByPage(String name, Integer page, Integer rows) {
        Example example = new Example(Author.class);
        Example.Criteria criteria = example.createCriteria();

        // 添加查询条件
        if (StringUtils.isNotBlank(name)) {
            criteria.andLike("name", "%" + name + "%");
        }

        // 添加分页
        PageHelper.startPage(page,rows);
        List<Author> authors = authorMapper.selectByExample(example);
        PageInfo<Author> pageInfo = new PageInfo<>(authors);

        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), authors);
    }
}
